<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="模板名称" prop="templateName">
        <el-input
          v-model="queryParams.templateName"
          placeholder="请输入模板名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:template:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:template:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:template:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:template:export']">导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="templateList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="模板id" align="center" prop="id" />
      <el-table-column label="模板名称" align="center" prop="templateName" />
      <el-table-column align="center" label="创建时间" prop="createTime"/>
      <el-table-column align="center" label="更新时间" prop="updateTime"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handlePreview(scope.row)"
          >预览
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:template:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:template:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 预览对话框 -->
    <el-dialog :visible.sync="previewVisible" append-to-body title="模板预览" width="500px">
      <template-preview :preview-data="previewData"/>
    </el-dialog>

    <!-- 添加或修改游戏模板对话框 -->
    <el-dialog :title="title" :visible.sync="open" append-to-body width="800px">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="模板名称" prop="templateName">
          <el-input v-model="form.templateName" placeholder="请输入模板名称" size="mini"/>
        </el-form-item>

        <el-card class="template-card">
          <div slot="header" class="card-header">
            <span>模板配置</span>
            <el-button size="mini" type="primary" @click="addCategory">添加分类</el-button>
          </div>
          <div class="template-config">
            <el-collapse v-model="activeNames">
              <el-collapse-item v-for="(category, index) in form.templateConfig" :key="index" :name="index">
                <template #title>
                  <div class="collapse-header">
                    <el-input v-model="category.name" placeholder="分类名称" size="mini" style="width: 200px"
                              @click.stop/>
                    <div class="header-actions">
                      <span class="action-label">添加：</span>
                      <el-switch
                        v-model="category.add"
                        size="mini"
                        style="margin-right: 10px"
                      />
                      <el-button circle icon="el-icon-delete" size="mini" style="color: red;font-size: 14px" type="text"
                                 @click.stop="removeCategory(index)"/>
                    </div>
                  </div>
                </template>
                <div class="control-list vertical">
                  <div v-for="(control, cIndex) in category.templateInfoList" :key="cIndex" class="control-item">
                    <div class="control-header">
                      <!-- 组合控件显示添加子控件按钮 -->
                      <el-button size="mini" type="primary"
                                 @click="addChildControl(control)">添加控件
                      </el-button>
                      <el-button circle icon="el-icon-delete" size="mini" style="color: red;font-size: 14px" type="text"
                                 @click="removeControl(index, cIndex)"/>
                    </div>
                    <!-- 组合控件的子控件配置 -->
                    <div class="composite-control">
                      <div v-for="(child, childIndex) in control" :key="childIndex" class="control-row">
                        <div class="child-control">
                          <el-select v-model="child.controlType" placeholder="控件类型" size="mini"
                                     style="width: 120px">
                            <el-option v-for="dict in dict.type.sys_control_type" :key="dict.value" :label="dict.label"
                                       :value="dict.value"/>
                          </el-select>
                          <el-input v-model="child.label" placeholder="标签名" size="mini" style="width: 120px"/>
                          <!-- 根据子控件类型显示不同的输入方式 -->
                          <div v-show="['2','7'].includes(child.controlType)">
                            <el-input v-model="child.placeholder" placeholder="提示信息" size="mini"
                                      style="width: 120px"/>
                          </div>
                          <template v-if="child.controlType === '3'">
                            <el-checkbox v-model="child.value" size="mini">选中</el-checkbox>
                          </template>
                          <template v-else-if="['4','5'].includes(child.controlType)">
                            <el-select v-model="child.value" placeholder="默认选中" size="mini"
                                       style="width: 120px">
                              <el-option v-for="option in child.options" :key="option.value" :label="option.label"
                                         :value="option.value"/>
                            </el-select>
                          </template>
                          <template v-else>
                            <template v-if="child.controlType === '6'">
                              <el-input-number v-model="child.number.value" :max="Number(child.number.max)"
                                               :min="Number(child.number.min)" :step="Number(child.number.step)"
                                               placeholder="默认值" size="mini" style="width: 120px"/>
                              <el-input v-model="child.number.min" placeholder="最小值" size="mini"
                                        style="width: 80px"/>
                              <el-input v-model="child.number.max" placeholder="最大值" size="mini"
                                        style="width: 80px"/>
                            </template>
                            <template v-else-if="child.controlType === '7'">
                              <el-date-picker
                                v-model="child.value"
                                class="control-value"
                                size="mini"
                                style="min-width: 130px"
                                type="date"
                              />
                            </template>
                            <el-input v-else v-model="child.value" placeholder="默认值" size="mini"
                                      style="width: 120px"/>
                          </template>
                          <!-- 子控件的禁用和必填开关 -->
                          <div class="control-switches">
                            <div v-if="child.controlType !== '1'">
                              <el-switch
                                v-model="child.disable"
                                size="mini"
                                style="margin-right: 5px"
                              />
                              <span style="margin-right: 10px">禁用</span>
                            </div>

                            <div v-if="child.controlType === '2'">
                              <el-switch
                                v-model="child.required"
                                size="mini"
                                style="margin-right: 5px"
                              />
                              <span>必填</span>
                            </div>
                          </div>
                          <!-- 下拉框显示添加选项按钮 -->
                          <el-button v-if="['4','5'].includes(child.controlType)" size="mini" type="primary"
                                     @click="addOption(child)">添加选项
                          </el-button>
                          <el-button circle icon="el-icon-delete" size="mini" style="color: red;font-size: 14px"
                                     type="text"
                                     @click="removeChildControl(control, childIndex)"/>
                        </div>
                        <!-- 下拉框的选项配置 -->
                        <div v-if="['4','5'].includes(child.controlType)" class="options-config">
                          <div v-for="(option, oIndex) in child.options" :key="oIndex" class="option-item">
                            <el-input v-model="option.label" placeholder="选项名称" size="mini" style="width: 120px"/>
                            <el-input v-model="option.value" placeholder="选项值" size="mini" style="width: 120px"/>
                            <el-button circle icon="el-icon-delete" size="mini" style="color: red;font-size: 14px"
                                       type="text" @click="removeOption(child, oIndex)"/>
                          </div>
                        </div>
                      </div>


                    </div>
                  </div>
                  <el-button size="mini" type="primary" @click="addControl(category)">添加行</el-button>
                </div>
              </el-collapse-item>
            </el-collapse>
          </div>
        </el-card>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" type="primary" @click="submitForm">确 定</el-button>
        <el-button size="mini" @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {addTemplate, delTemplate, getTemplate, listTemplate, updateTemplate} from "@/api/template/game";
import TemplatePreview from "@/layout/components/Template/TemplatePreview.vue";

export default {
  name: "Template",
  components: {TemplatePreview},
  dicts: ['sys_control_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 游戏模板表格数据
      templateList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        templateName: null,
        templateConfig: null,
      },
      // 表单参数
      form: {
        id: null,
        templateName: null,
        templateConfig: []
      },
      // 表单校验
      rules: {
        templateName: [
          {required: true, message: '模板名称不能为空', trigger: 'blur'}
        ]
      },
      // 预览相关
      previewVisible: false,
      previewData: {
        templateName: '',
        templateConfig: []
      },
      activeNames: [], // 当前展开的折叠面板
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询游戏模板列表 */
    getList() {
      this.loading = true;
      listTemplate(this.queryParams).then(response => {
        this.templateList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        templateName: null,
        templateConfig: []
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = '添加游戏模板';
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getTemplate(id).then(response => {
        if (response.data) {
          this.form = {
            ...response.data,
            templateConfig: Array.isArray(response.data.templateConfig) ? response.data.templateConfig : []
          };
          this.activeNames = this.form.templateConfig.map((_, index) => index);
          this.open = true;
          this.title = '修改游戏模板';

        } else {
          this.$modal.msgError('获取模板数据失败');
        }
      }).catch(() => {
        this.$modal.msgError('获取模板数据失败');
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateTemplate(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTemplate(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除游戏模板编号为"' + ids + '"的数据项？').then(function() {
        return delTemplate(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/template/export', {
        ...this.queryParams
      }, `template_${new Date().getTime()}.xlsx`)
    },
    // 添加分类
    addCategory() {
      this.form.templateConfig.push({
        name: '',
        templateInfoList: []
      });
    },
    // 删除分类
    removeCategory(index) {
      this.form.templateConfig.splice(index, 1);
    },
    // 添加控件
    addControl(category) {
      category.templateInfoList.push([{
        controlType: '1', // 默认文本框
        label: '',
        value: null,
        placeholder: '',
        required: false,
        disable: false,
        options: [],
        children: []
      }]);
    },
    // 删除控件
    removeControl(categoryIndex, controlIndex) {
      this.form.templateConfig[categoryIndex].templateInfoList.splice(controlIndex, 1);
    },
    // 添加选项
    addOption(child) {
      if (!child.options) {
        child.options = [];
      }
      child.options.push({
        label: '',
        value: ''
      })
    },
    // 删除选项
    removeOption(child, optionIndex) {
      child.options.splice(optionIndex, 1);
    },
    // 添加子控件
    addChildControl(control) {
      control.push({
        controlType: '1',
        label: '',
        value: null,
        number: {},
        placeholder: '',
        disable: false
      });
    },
    // 删除子控件
    removeChildControl(control, childIndex) {
      control.splice(childIndex, 1);
    },
    // 预览按钮操作
    handlePreview(row) {
      if (!row || !row.templateConfig) {
        this.$modal.msgError('预览数据无效');
        return;
      }
      try {
        this.previewData = {
          templateName: row.templateName,
          templateConfig: Array.isArray(row.templateConfig) ? row.templateConfig : []
        };
        this.previewVisible = true;
      } catch (error) {
        this.$modal.msgError('预览数据解析失败');
      }
    }
  }
};
</script>

<style scoped>
.template-card {
  margin-bottom: 20px;
  font-size: 12px;
}

.template-card ::v-deep(.el-card__header) {
  padding: 10px 20px;
  border-bottom: 1px solid #ebeef5;
  font-size: 12px;
}

.template-config {
  padding: 20px;
  max-height: 500px;
  overflow-y: auto;
  font-size: 12px;
}

.template-config::-webkit-scrollbar {
  width: 6px;
}

.template-config::-webkit-scrollbar-thumb {
  background-color: #909399;
  border-radius: 3px;
}

.template-config::-webkit-scrollbar-track {
  background-color: #f5f7fa;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
}

.control-list {
  font-size: 12px;
}

.control-list.horizontal {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.control-list.vertical {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.control-item {
  border-radius: 4px;
  display: flex;
  flex-direction: column;
  gap: 10px;
  font-size: 12px;
}

.control-header {
  display: flex;
  align-items: center;
  gap: 10px;
  justify-content: flex-start;
  font-size: 12px;
}

.options-config {
  display: flex;
  flex-direction: column;
  gap: 10px;
  font-size: 12px;
}

.option-item {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 12px;
}

.composite-control {
  display: flex;
  flex-direction: column;
  justify-content: space-between;

  gap: 10px;
}


.child-control {
  display: flex;
  align-items: center;
  gap: 5px;
  margin-right: 10px;
  flex: 0 0 auto;
  min-width: 200px;
}

::v-deep(.el-card__header) {
  padding: 10px 20px;
  border-bottom: 1px solid #ebeef5;
  font-size: 12px;
}

::v-deep(.el-card__body) {
  padding: 20px;
  font-size: 12px;
}

.collapse-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  padding-right: 20px;
  font-size: 12px;
}

::v-deep(.el-collapse-item__header) {
  padding: 0 20px;
  height: 48px;
  line-height: 48px;
  font-size: 12px;
}

::v-deep(.el-collapse-item__content) {
  padding: 20px;
  font-size: 12px;
}


::v-deep(.el-card__header) {
  padding: 10px 20px;
  border-bottom: 1px solid #ebeef5;
  font-size: 12px;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 12px;
}

.action-label {
  color: #606266;
  font-size: 12px;
}

.control-switches {
  display: flex;
  align-items: center;
  gap: 5px;
  margin-left: auto;
  font-size: 12px;
  white-space: nowrap;
}

.control-switches span {
  font-size: 12px;
}

::v-deep(.el-dialog__title) {
  font-size: 12px;
}

::v-deep(.el-dialog__body) {
  font-size: 12px;
}

::v-deep(.el-dialog__footer) {
  font-size: 12px;
}

.composite-control.horizontal {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  align-items: center;
}

.child-control {
  display: flex;
  align-items: center;
  gap: 5px;
  margin-right: 10px;
}

.control-row {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 10px;
}
.control-list.vertical .control-item {
  width: 100%;
  margin-bottom: 10px;
}
</style>
